﻿using MemoryPack;

namespace sgf.server
{
    [MemoryPackable]
    public partial class Message
    {
        public string MsgType;

        [BrotliFormatter] public byte[] data;


        private Type GetType()
        {
            return Type.GetType(MsgType);
        }

        public object GetDataObj()
        {
            //return BsonHelper.FromBson(GetType(), data);
            return MemoryPackSerializer.Deserialize(GetType(), data);
        }

        public byte[] ToBytes()
        {
            return MemoryPackSerializer.Serialize(this);
            // return BsonHelper.ToBson(this);
        }

        public static Message CreateMessage<T>(T obj)
        {
            return new Message
            {
                MsgType = typeof(T).FullName,
                // data = BsonHelper.ToBson(obj)
                data = MemoryPackSerializer.Serialize(obj)
            };
        }

        public static Message FromBytes(byte[] bytes)
        {
            return MemoryPackSerializer.Deserialize<Message>(bytes);
            // return BsonHelper.FromBson<Message>(bytes);
        }
    }
}